//
//  AppDelegate.m
//  rrqs
//
//  Created by kyjun on 16/3/23.
//
//

#import "AppDelegate.h"
#import <RESideMenu/RESideMenu.h>

#import "LeftController.h"
#import "HomeController.h"
#import "Location.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AFNetworking/AFNetworkActivityIndicatorManager.h>
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <IQKeyboardManager/IQToolbar.h>
#import <AdSupport/AdSupport.h>
#import "JPUSHService.h"

@interface AppDelegate ()<RESideMenuDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    // [self launchScreen];
    [self settingsGlobalStyle];
    [self locationManger:launchOptions];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:[[HomeController alloc] init]];
    LeftController *leftMenuViewController = [[LeftController alloc] init];
    
    RESideMenu *sideMenuViewController = [[RESideMenu alloc] initWithContentViewController:navigationController
                                                                    leftMenuViewController:leftMenuViewController
                                                                   rightMenuViewController:nil];
//      sideMenuViewController.backgroundImage = [UIImage imageNamed:@"Stars"];
    sideMenuViewController.menuPreferredStatusBarStyle = 1;
    sideMenuViewController.delegate = self;
    sideMenuViewController.contentViewShadowColor = [UIColor whiteColor];
    sideMenuViewController.contentViewShadowOffset = CGSizeMake(0, 0);
    sideMenuViewController.contentViewShadowOpacity = 0.6;
    sideMenuViewController.contentViewShadowRadius = 12;
    sideMenuViewController.contentViewShadowEnabled = YES;
    sideMenuViewController.scaleContentView = NO;
    sideMenuViewController.contentViewInLandscapeOffsetCenterX = 120.f;
    sideMenuViewController.contentViewInPortraitOffsetCenterX  = 120.f;
    sideMenuViewController.scaleContentView = NO;
    sideMenuViewController.scaleMenuView = NO;
    
    self.window.rootViewController = sideMenuViewController;
    [self.window makeKeyAndVisible];
    
    [self startJPush:launchOptions];
    
    [AMapServices sharedServices].apiKey = @"1eb6a5acbafbfec8da1909a71f7f27f9";
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    /* if ([CLLocationManager significantLocationChangeMonitoringAvailable])
     {
     [[Location sharedManager].locationManager stopUpdatingLocation];
     [[Location sharedManager ].locationManager startMonitoringSignificantLocationChanges];
     NSLog(@"Significant location change monitoring is available.");
     }
     else
     {
     NSLog(@"Significant location change monitoring is not available.");
     }*/
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    /*if ([CLLocationManager significantLocationChangeMonitoringAvailable])
     {
     [[Location sharedManager].locationManager stopUpdatingLocation];
     [[Location sharedManager ].locationManager startMonitoringSignificantLocationChanges];
     NSLog(@"Significant location change monitoring is available.");
     }     else     {
     NSLog(@"Significant location change monitoring is not available.");
     }*/
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required
    [JPUSHService handleRemoteNotification:userInfo];
    [self handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    [self handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification  completionHandler:(void (^)())completionHandler {
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
}
#endif

-(void)settingsGlobalStyle{
    
    NSDictionary *navbarTitleTextAttributes = @{NSForegroundColorAttributeName:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0],NSFontAttributeName:[UIFont boldSystemFontOfSize:17.f]};
    [[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];
    //  [[UINavigationBar appearance] setBackgroundColor:theme_navigation_color];
    //[[UINavigationBar appearance] setBarTintColor:theme_navigation_color];
    [[UINavigationBar appearance] setTintColor:theme_default_color];
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
    
//    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];//将title 文字的颜色改为透明
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"icon-navigation"] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
    
    [[UIToolbar appearance] setBarTintColor:theme_navigation_color];
    
    [[UITableView appearance] setBackgroundColor:theme_table_bg_color];
    [[UICollectionView appearance] setBackgroundColor:theme_table_bg_color];
    
    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
    [NSURLCache setSharedURLCache:URLCache];
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    [[IQToolbar appearance] setBarTintColor:theme_navigation_color];
    [[IQToolbar appearance] setTintColor:theme_default_color];
    
}

-(void)locationManger:(NSDictionary *)launchOptions{
    
    [Location sharedManager];
}

#pragma mark =====================================================  RESideMenu Delegate

- (void)sideMenu:(RESideMenu *)sideMenu willShowMenuViewController:(UIViewController *)menuViewController
{
    NSLog(@"willShowMenuViewController: %@", NSStringFromClass([menuViewController class]));
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationUpdateUserAccount object:nil];
}

- (void)sideMenu:(RESideMenu *)sideMenu didShowMenuViewController:(UIViewController *)menuViewController
{
    NSLog(@"didShowMenuViewController: %@", NSStringFromClass([menuViewController class]));
}

- (void)sideMenu:(RESideMenu *)sideMenu willHideMenuViewController:(UIViewController *)menuViewController
{
    NSLog(@"willHideMenuViewController: %@", NSStringFromClass([menuViewController class]));
}

- (void)sideMenu:(RESideMenu *)sideMenu didHideMenuViewController:(UIViewController *)menuViewController
{
    NSLog(@"didHideMenuViewController: %@", NSStringFromClass([menuViewController class]));
}

#pragma mark =====================================================  设置极光推送
-(void)startJPush:(NSDictionary*)launchOptions{
    
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
   /*接收自定义消息 NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];*/
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert) categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert) categories:nil];
    }
    /*
     if (DEBUG) {
     [JPUSHService setupWithOption:launchOptions appKey:appKey
     channel:nil
     apsForProduction:NO advertisingIdentifier:advertisingId];
     }else{*/
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:nil
                 apsForProduction:YES  advertisingIdentifier:advertisingId];
    /* }*/
    
}

#pragma mark =====================================================  远程通知
/**
 *  接收通知
 *
 *  @param remoteInfo
 */
-(void)handleRemoteNotification:(NSDictionary *)remoteInfo{
    NSLog(@"通知:%@",remoteInfo);
    if(![WMHelper isNULLOrnil:remoteInfo])
    {
        if([[MSingle shareAuhtorization].userInfo.close isEqualToString:@"1"]){
            NSString* notificationType = [remoteInfo objectForKey:@"qs_type"];
            if([notificationType isEqualToString:@"at"]){
                [self PayAudio:@"push_to_order.mp3"];
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationRemoteAt object:nil];
            }else if([notificationType isEqualToString:@"pm"]){
                [self PayAudio:@"push_by_system.mp3"];
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationHomeRefreshing object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationRemotePm object:nil];
            }else{
                
            }
        }
    }

}

/**
 *  接收自定义消息
 *
 *  @param notification
 */
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSLog(@"自定义消息:%@",userInfo);
    if(![WMHelper isNULLOrnil:userInfo])
    {
        if([[MSingle shareAuhtorization].userInfo.close isEqualToString:@"1"]){
            NSDictionary* dict = [userInfo objectForKey:@"extras"];
            NSString* notificationType = [dict objectForKey:@"qs_type"];
            if([notificationType isEqualToString:@"at"]){
                [self PayAudio:@"push_to_order.mp3"];
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationRemoteAt object:nil];
            }else if([notificationType isEqualToString:@"pm"]){
                [self PayAudio:@"push_by_system.mp3"];
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationHomeRefreshing object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationRemotePm object:nil];
            }else{
                
            }
        }
    }
}

-(void)PayAudio:(NSString*)fileName{
    NSString *path = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], fileName];
    
    SystemSoundID soundID;
    
    NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
    
    //Use audio sevices to create the sound
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);
    //Use audio services to play the sound
    AudioServicesPlaySystemSound(soundID);
}

@end
